package com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.web;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.aliyun.gts.bpaas.framework.api.rest.dto.ResultResponse;
import com.aliyun.gts.delivery.enterprise.sdk.common.PageQuery;
import com.aliyun.gts.delivery.enterprise.sdk.common.PageResult;
import com.aliyun.gts.delivery.enterprise.sdk.orgaccount.out.AccountInfo;
import com.aliyun.gts.delivery.enterprise.sdk.orgaccount.out.OrganizationInfo;
import com.github.pagehelper.PageInfo;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.enums.UserEnum;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.UserGroupService;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.UserPositionService;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl.OrgAccountServiceAdapter;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl.RbacServiceAdapter;
import com.iwhalecloud.citybrain.flow.platform.manager.common.ResponseResult;
import com.iwhalecloud.citybrain.flow.platform.manager.common.ResultForService;
import com.iwhalecloud.citybrain.flow.platform.manager.common.UserGroup;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.FlowFunctionConfigVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.foura.FourAOrgQueryVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.userentity.EmployeeInfo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.userentity.GroupInfo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.userentity.PositionInfo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.userentity.UserInfo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.userentity.vo.SelectPositionUserReq;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowFunctionConfigRepository;
import com.xxl.sso.core.login.SsoWebLoginHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author twf
 */
@Slf4j
@RestController
@RequestMapping(value = "/4A")
@Api(value = "4A", tags = {"4A接口"})
public class FouraController {

    @Autowired(required = false)
    private OrgAccountServiceAdapter orgAccountService;

    @Autowired
    private RbacServiceAdapter rbacServiceAdapter;

    @Autowired
    FlowFunctionConfigRepository flowFunctionConfigRepository;


    private Logger  logger  = LoggerFactory.getLogger(this.getClass());

    /**
     * 获取用户详细信息
     */
    @ApiOperation("获取用户详细信息")
    @RequestMapping(value = "/getUserAndExtUserByCode")
    public ResponseResult getUserAndExtUserByCode() {
        System.out.println("客户端查询当前登录用户");
        ResultResponse<AccountInfo> currentAccountInfo = orgAccountService.getCurrentAccountInfo();
        Map<String, Object> map = new HashMap<>();
        map.put("USER_CODE", currentAccountInfo.getData().getCode());
        map.put("USER_ID", currentAccountInfo.getData().getExtentAttributes().get("USER_ID"));
        map.put("USER_NAME", currentAccountInfo.getData().getUsername());
        ResultForService userAndExtUserByCode = new ResultForService(ResultForService.SUCCESS, currentAccountInfo.getMessage(),
                map);
        log.info("用户信息：{}", JSONUtil.toJsonStr(currentAccountInfo.getData()));
        return ResponseResult.success(currentAccountInfo.getData());
    }

    /**
     * 根据UserCode获取权限列表，返回前端
     */
    @ApiOperation("根据UserCode获取权限列表")
    @RequestMapping(value = "/getResourceListByUserCode")
    public ResponseResult getResourceListByUserCode() {
        //Set<String> set = new HashSet<>(Arrays.asList("/model/list-url", "/tenant/delete-url", "/task/claim-url", "page-ProcessExecute-Handle-Todo", "/file/download", "/app/authorized/users", "/form/list", "icon-entry-tenant-add", "/model/deploy", "icon-app-authorize-add", "/model/detail-url", "/app/detail-url", "/file/add", "/tenant/add-url", "/process/diagramAndInfo", "page-Homepage", "/app/listAll", "page-ProcessInstanceMonitor", "/app/authorize/cancel-url", "/model/save-url", "page-SystemManage-Busi", "/4A/getRootOrg", "icon-entry-process-instance-end", "page-ProcessMonitor", "/task/form", "page-SystemManage-AppAuthorize", "icon-entry-model-deploy", "/form/save", "/4A/getRootOrg-url", "/process/processed-url", "/todo/claim", "/process/processed", "page-ProcessExecuteDetail", "/model/delete", "/4A/getResourceListByUserCode", "page-4a-user-tree", "/app/delete", "/busi/update", "/todo/handle", "page-Report", "/task/rollback/list", "/tenant/edit-url", "/model/deployment/detail", "page-Report-FlowTaskTotal", "/process/handle-url", "/form/copy", "/model/candidateGroups-url", "page-SystemManage-WorkdingDay", "/process/apply-url", "icon-entry-process-instance-recall", "page-ProcessExecute-Todo", "page-ProcessExecute-Handle", "page-TaskInstanceMonitor", "/notice/detail", "icon-entry-process-instance-active", "page-MyMessage-Detail", "/app/authorize/cancel", "/task/handle", "/app/add", "/tenant/edit", "page-ProcessManage", "/tenant/add", "/form/delete", "page-SystemManage-SetWeekDays", "/4A/getUserAndExtUserByCode", "icon-entry-process-instance-rollback", "/model/create", "/busi/update-url", "/notice/msgtype", "icon-system-manage-app-busi-add", "/model/candidateGroups", "/task/skip/list", "/model/deploy-url", "icon-entry-model-delete", "page-Report-FlowInstanceDetail", "/process/handleLogs", "icon-entry-form-preview", "icon-entry-form-copy", "icon-entry-model-edit", "/busi/delete", "page-Report-FlowTaskDetail", "/app/list", "/app/edit-url", "/form/create", "/tenant/delete", "icon-system-manage-app-edit", "/4A/getOrgsByParentCode-url", "page-SystemManage-Tenant", "/process/currentTasks", "/app/authorize/user-url", "icon-entry-form-modify", "/notice/updateReadStatus", "/app/authorize/user", "/4A/logout", "/model/deployment/list", "icon-entry-model-add", "page-SystemManage-Notification", "/app/authorized/users-url", "/count/count", "/4A/getUserByOrgCode-url", "/app/detail", "/model/detail", "page-Task-Relate", "/app/delete-url", "/process/list-url", "icon-entry-process-instance-suspend", "icon-app-authorize-cancel", "/notice/list", "icon-system-manage-app-del", "/process/todo-url", "/task/skip-url", "page-MyMessage", "icon-system-manage-busi-edit", "/process/todo", "/busi/add", "page-ProcessInstance-Relate", "/task/rollback", "page-TaskCenter-Detail", "/busi/add-url", "/task/handle-url", "page-FlowHome", "icon-entry-process-instance-jump", "/model/save", "/model/copy", "notice-relate", "page-ProcessRulesMonitor", "/task/claim", "/tenant/list", "/model/create-url", "icon-system-manage-busi-del", "page-ProcessExecute-Handle-MyApply", "/4A/getOrgsByParentCode", "page-SystemManage-App", "/busi/delete-url", "icon-entry-process-execute-apply", "page-TaskCenter", "page-ProcessExecute-Handle-Processed", "icon-entry-form-add", "/process/list", "page-SystemManage-App-Authorize", "page-MyTodo", "/app/add-url", "page-ProcessExecuteApply", "icon-entry-tenant-delete", "icon-entry-form-delete", "page-ProcessExecuted", "page-Report-FlowInstanceTotal", "/task/skip", "/tenant/list-url", "/app/edit", "page-CommonInterface", "page-SystemManage-AppBusi", "icon-entry-model-copy", "/model/delete-url", "/form/detail", "icon-entry-tenant-edit", "/process/handle", "page-ProcessConfig", "/4A/getUserByOrgCode", "/process/apply", "page-SystemManage", "/process/start", "page-MyTodo-Detail", "page-Process-Handle-MyApply", "page-Process-Handled", "/model/list", "page-FlowList", "page-FormConfig"));
        return ResponseResult.success(rbacServiceAdapter.getCurrentUserMenuResource());
    }


    /**
     * 通过机构编码获取下级机构数据
     *
     * @param fourAOrgQueryVo
     * @return
     */
    @ApiOperation("通过机构编码获取下级机构数据")
    @RequestMapping(value = "/getOrgsByParentCode", method = RequestMethod.POST)
    public ResponseResult getOrgsByParentCode(@RequestBody FourAOrgQueryVo fourAOrgQueryVo) {
        List<OrganizationInfo> organizationInfos = orgAccountService.getOrganizationInfoByParentCode(fourAOrgQueryVo.getOrgCode()).getData();
        List<Map<String, Object>> dataList = new ArrayList<>();
        if(organizationInfos != null){
            for (OrganizationInfo organizationInfo : organizationInfos) {
                dataList.add(organizationInfo.getExtentAttribute());
            }
        }

        log.info("查询子组织信息：{}", JSONUtil.toJsonStr(organizationInfos));
        return ResponseResult.response(new ResultForService(ResultForService.SUCCESS, ResultForService.SUCCESS_MSG, organizationInfos));
    }

    /**
     * 通过机构编码获取机构下人员数据（本层级）
     */
    @ApiOperation("通过机构编码获取机构下人员数据（本层级）")
    @RequestMapping(value = "/getUserByOrgCode", method = RequestMethod.POST)
    public ResponseResult getUserByOrgCode(@RequestBody FourAOrgQueryVo fourAOrgQueryVo) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageSize(fourAOrgQueryVo.getPageSize());
        pageQuery.setPageNumber(fourAOrgQueryVo.getPageNo());
        List<Map<String, Object>> dataList = new ArrayList<>();
        PageResult<AccountInfo> accountInfoPageResult = orgAccountService.getOrganizationMembersByOrgCode(pageQuery, fourAOrgQueryVo.getOrgCode()).getData();
        List<AccountInfo> accountInfos = new ArrayList<>();
        if(accountInfoPageResult != null){
            accountInfos = accountInfoPageResult.getRows();
            for (AccountInfo accountInfo : accountInfos) {
                dataList.add(accountInfo.getExtentAttributes());
            }
        }

        log.info("获取组织下面人员信息：{}", JSONUtil.toJsonStr(accountInfos));
        return ResponseResult.response(new ResultForService(ResultForService.SUCCESS, ResultForService.SUCCESS_MSG, accountInfos));
    }

    /**
     * 获取机构根节点
     *
     * @return
     */
    @ApiOperation("获取机构根节点")
    @RequestMapping(value = "/getRootOrg")
    public ResponseResult getRootOrg() {

        List<OrganizationInfo> rootOrganization = orgAccountService.getRootOrg().getData();
        log.info("获取根组织信息：{}", JSONUtil.toJsonStr(rootOrganization));
        return ResponseResult.success(rootOrganization);
        /*OrganizationInfo rootOrganization = orgAccountService.getRootOrganization().getData();
        ResultForService response = new ResultForService(ResultForService.SUCCESS, ResultForService.SUCCESS_MSG, rootOrganization.getExtentAttribute());
        log.info("获取根组织信息：{}", JSONUtil.toJsonStr(rootOrganization));
        return ResponseResult.success(rootOrganization);*/
    }

    /**
     * 根据用户名模糊查询用户信息
     *
     * @return
     */
    @ApiOperation("根据用户名模糊查询用户信息")
    @RequestMapping(value = "/getUserListByNameFuzzy", method = RequestMethod.POST)
    public ResultResponse<List<AccountInfo>> getUserListByNameFuzzy(String username) {

        return orgAccountService.getAccountByNameFuzzy(username);
    }

    @PostMapping("/logout")
    public ResponseResult<Map<String, String>>  logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ResultResponse<AccountInfo> currentAccountInfo = orgAccountService.getCurrentAccountInfo();
        AccountInfo  account  =  currentAccountInfo.getData();
        String code = null;
        String username = null;
        if(account != null){
            code  = account.getCode();
            username  = account.getUsername();
        }
        logger.info("Log Out, Code:"+code +" Username:"+username);
        SsoWebLoginHelper.logout(request, response);
        Map data  = new HashMap();
        data.put("logoutUrl","http://127.0.0.1/flow-web/");
        ResponseResult<Map<String, String>> ret = ResponseResult.success(data);
        logger.info("LogOut Ret:");
        logger.info(JSON.toJSONString(ret, SerializerFeature.PrettyFormat));
        return   ret;
    }


    /**
     * 获取用户组列表
     * @return
     */
    @ApiOperation("获取用户组列表")
    @RequestMapping(value = "/getAllUserGroupList", method = RequestMethod.POST)
    public ResponseResult<List<UserGroup>>  getAllUserGroupList(){
        ResultResponse<List<UserGroup>> allUserGroupList = orgAccountService.getAllUserGroupList();
        return  ResponseResult.success(allUserGroupList.getData());
    }


    /**
     * 获取自定义函数列表
     *
     * @return
     */
    @ApiOperation("获取自定义函数列表")
    @RequestMapping(value = "/getAllFunctionConfigList", method = RequestMethod.GET)
    public ResponseResult getAllFunctionConfigList() {
        return ResponseResult.success(flowFunctionConfigRepository.getAllFunctionConfigList());
    }


    public static void main(String[] args) {
        String type = UserEnum.SUPER.type();
        System.out.println(type);
    }

}
